/**
 * Deck.java
 * 
 * (C) 2011 - Mischa Spelt (m.spxxxelt@gmail.com - remove xxx)
 * 
 */
package com.mischa.doedeljas;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * Represents the 32-card playing deck of cards
 * 
 * @author Mischa spelt
 * 
 */
public class Deck {
	/**
	 * All the cards in an ordinary deck, used as prototype
	 * for constructing new decks.
	 */
	private static Collection<Card> deck = null;

	/**
	 * Initialise the prototype deck with all 32 cards.
	 */
	private static void initialiseDeck() {
		deck = new Vector<Card>();
		for (int suit = 1; suit <= 4; ++suit) {
			for (int value = 1; value <= 8; ++value) {
				deck.add(new Card(10 * suit + value));
			}
		}
	}

	/**
	 * A list of all the undealt cards in this deck.
	 */
	private List<Card> undealt = new ArrayList<Card>();

	/**
	 * Random number generator
	 */
	private final Random randomGenerator = new Random();

	/**
	 * Constructor
	 */
	public Deck() {
		if (deck == null) {
			initialiseDeck();
		}

		reset();
	}

	/**
	 * Deal a card from the deck.
	 * 
	 * @return
	 * 		A card which has not yet been dealt, or null if all cards have been dealt.
	 */
	public Card dealCard() {
		if (undealt.isEmpty()) {
			return null;
		}

		final int index = randomGenerator.nextInt(undealt.size());
		return undealt.remove(index);
	}

	/**
	 * Get the remaining number of undealt cards in the deck.
	 * 
	 * @return
	 * 		The remaining number of undealt cards in the deck
	 */
	public int getUndealtCards() {
		return undealt.size();
	}

	/**
	 * Reset the deck to its initial state with 32 undealt cards.
	 */
	public void reset() {
		undealt = new Vector<Card>();
		undealt.addAll(deck);
	}

}
